package com.retry.task.admin.controller;

import com.retry.task.admin.constants.Constants;
import com.retry.task.admin.biz.service.UserInfoBizService;
import com.retry.task.admin.dal.model.UserInfoDO;
import com.retry.task.admin.dal.model.query.UserInfoQuery;
import com.retry.task.admin.session.SessionInfo;
import com.retry.task.admin.utils.AesUtils;
import com.retry.task.admin.utils.CookieUtil;
import com.retry.task.core.model.base.PageResult;
import com.retry.task.core.model.base.Result;
import com.retry.task.core.utils.GsonTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author gao.gwq
 * @version 1.0
 * @date 2022/4/21  17:00
 * @Description TODO
 */
@RequestMapping("/retrytask")
@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserInfoBizService userInfoService;

    @RequestMapping("/loginOut")
    @ResponseBody
    public Result<String> loginOut(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CookieUtil.setCookie(request, response, "user_token", "null", 0);
        setResponseRedirect(response);
        return Result.getSuccess("login sucess");
    }

    private void setResponseRedirect(HttpServletResponse httpResponse) throws IOException {
        httpResponse.setStatus(200);
        Result result = Result.getFail("-999", "redirect");
        httpResponse.getWriter().write(GsonTool.toJsonStringIgnoreNull(result));
        httpResponse.setContentType("application/json; charset=UTF-8");
        httpResponse.setHeader("Redirect", "true");
        httpResponse.setHeader("RedirectUrl", "/admin/login.html");
        httpResponse.flushBuffer();
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result<String> login(String userName, String password, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(userName)) {
            return Result.getFail("100", "username is null");
        }
        if (StringUtils.isEmpty(password)) {
            return Result.getFail("100", "password is null");
        }
        UserInfoQuery query = new UserInfoQuery();
        query.setIsTest(isTest);
        query.setUserName(userName);
        query.setPassword(password);
        PageResult<List<UserInfoDO>> pageResult = userInfoService.findUser(query);
        if (!pageResult.isSuccess()) {
            return Result.getFail(pageResult.getCode(), pageResult.getErrMsg());
        }
        List<UserInfoDO> list = pageResult.getData();
        if (CollectionUtils.isEmpty(list)) {
            return Result.getFail("100", "用户名或者密码错误");
        }
        setCookie(request, response, list);
        return Result.getSuccess("login sucess");
    }

    private void setCookie(HttpServletRequest request, HttpServletResponse response, List<UserInfoDO> list)
        throws Exception {
        UserInfoDO userInfoDO = list.get(0);
        SessionInfo sessionInfo = new SessionInfo();
        BeanUtils.copyProperties(userInfoDO, sessionInfo);
        sessionInfo.setLastTime(System.currentTimeMillis());
        String cookVal = GsonTool.toJsonStringIgnoreNull(sessionInfo);
        /*String realCookieVal = String.valueOf(RSACoder.encryptByPublicKey(cookVal.getBytes(StandardCharsets.UTF_8),
            Constants.publicKey));*/
        String realCookieVal = AesUtils.encrypt(cookVal, Constants.CODE_KEY);
        CookieUtil.setCookie(request, response, "user_token", realCookieVal, 24 * 3600);
    }

}
